const {body} = require('express-validator')
const validate = require('../middleware/validate')
const User = require('../models/User')
const {decrypt} = require('../utils/utils')

//注册
exports.register = validate([
  body('username')
    .notEmpty().withMessage('用户名不能为空')
    .custom(async username => {
      const user = await User.findOne({username})
      if (user) {
        return Promise.reject('用户名已存在')
      }
    }),
  body('password').notEmpty().withMessage('密码不能为空'),

  body('email')
    .notEmpty().withMessage('邮箱不能为空')
    .isEmail().withMessage('邮箱格式不正确')
    .bail()
    .custom(async email => {
      const user = await User.findOne({email})
      if (user) {
        return Promise.reject('邮箱已存在')
      }
    })
])

//登陆
exports.login = [
  validate([
    body('username').notEmpty().withMessage('用户名不能为空'),
    body('password').notEmpty().withMessage('密码不能为空')
  ]),
  validate([
    body('username').custom(async (username, {req}) => {
      console.log('username: ', username);
      const user = await User.findOne({username}).select('+password')
      console.log('user: ', user);
      if (!user) {
        return Promise.reject('用户不存在')
      }
      // 将数据挂载到请求对象中，后续的中间件也可以使用了
      req.user = user
    })
  ]),
  validate([
    body('password').custom(async (password, {req}) => {
      console.log('密码: ', password);
      console.log('解密的密码: ', decrypt(password));
      console.log('数据库存的密码: ', req.user.password);
      console.log('解密的密码是否等于数据库解密的密码：', decrypt(password) == decrypt(decrypt(req.user.password)));
      if (decrypt(password) !== decrypt(decrypt(req.user.password))) {
        return Promise.reject('登录密码错误')
      }
    })
  ])
]

exports.changeRole = validate([
  body('id').notEmpty().withMessage('id不能为空'),
  body('roles').notEmpty().withMessage('roles不能为空')
])
